package com.example.client_fmf;

//import com.example.clientserver.Connexion;
//import com.example.clientserver.R;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class MainActivity extends ActionBarActivity implements AsyncResponse {
	

	final int CODE = 0  ; 
	final int MSG_TEXT = 1  ; 
	public static String myId = "" ; 
	public static String partnerId = "" ; 
	
	final static String  host = "192.168.2.11";
	final static int port = 3000;
	static Connection cnt; 
	final String DISCONNECT = "000" ; 
	final String REQUEST_ID  = "001";
	final String REQUEST_PARTNER = "010";
	final String LOCATION_PARAMETER = "011";	
	final String RECEIVE_PARTNER_LOCATION = "110";
	final String ASK_FOR_PARTNER = "100";
	final String MAKE_CONNECTION = "101";
	final String READY = "111" ; 
	
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		
		
		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	public void connect(View view) throws IOException
	{
		
		
		connectToServer(host , port) ; 
		//cnt.startReceiving() ; 
	}
	private void ready() throws UnsupportedEncodingException
	{
		//cnt.send(formatMsg(READY,"")) ; 
		
	}
	private void  connectToServer(String host , int port) throws UnsupportedEncodingException
	{
		cnt = new Connection() ; 		
		cnt.delegate = this;
		cnt.connect(host, port);
		cnt.send(formatMsg(REQUEST_ID,""));
	}
	public void connectToPartner(View view) throws UnsupportedEncodingException
	{

		EditText editText = (EditText) findViewById(R.id.partnerId);
		String msg = editText.getText().toString();		
		partnerId = msg ; 
		String textToSend = formatMsg(REQUEST_PARTNER , partnerId) ; 		 
		cnt.send(textToSend);
		
	}
	private String formatMsg(String code , String msg)
	{
		String formatedMsg  = code+"-"+ myId + "-" +msg+"-" ; 
		return formatedMsg ; 
	}
	private void processGoogleMap()
	{
		Intent intent = new Intent(this, MapActivity.class);
		startActivity(intent);
		finish() ; 
	}
	
	private void treatResponse(String response) throws UnsupportedEncodingException
	{
		if(response.equalsIgnoreCase("true"))
			processGoogleMap() ;
		else
		{
			EditText editText = (EditText) findViewById(R.id.partnerId);
			editText.setText("");
		}
	}
	private void manageReceivedMsg(String msg) throws UnsupportedEncodingException
	{
		 String[] msgTab = msg.split("-") ; 
		
		switch(msgTab[CODE])
		{
			case REQUEST_ID : DisplayId(msgTab[MSG_TEXT]) ; break ; 
			
			//case ASK_FOR_PARTNER : answerPartner() ; break;  
			case MAKE_CONNECTION : treatResponse(msgTab[MSG_TEXT]) ;  break ; 
			case RECEIVE_PARTNER_LOCATION : break ;
		
			case DISCONNECT : closeConnexion(); break ;
			default : break ;
		}
		
		
	}
	
	private void closeConnexion()
	{
		cnt.close();
	}
	private void DisplayId(String text)
	{
		myId = text ; 
		TextView textView = (TextView) findViewById(R.id.myId);
		textView.setText(text);
		EnableControls() ; 

	}
	
	
	
	
	public void disconnect(View view) throws IOException
	{
		disconnect() ; 
	}
	private void disconnect() 
	{
		DisableControls() ; 
		try {
			
			cnt.send(formatMsg(DISCONNECT , ""));
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//cnt.close();
		
		
	}
	private void EnableControls()
	{
		TextView textView = (TextView) findViewById(R.id.myId);	
		Button partnerBtn = (Button) findViewById(R.id.connectToPartner) ; 	
		EditText textBox  = (EditText) findViewById(R.id.partnerId) ;	
		Button cntBtn = (Button) findViewById(R.id.connect) ; 	
		Button DiscBtn = (Button) findViewById(R.id.disconnect) ; 
		
		partnerBtn.setEnabled(true);
		textBox.setEnabled(true); 		
		DiscBtn.setEnabled(true); 
		cntBtn.setEnabled(false);
	}
	private void DisableControls()
	{
		TextView textView = (TextView) findViewById(R.id.myId);	
		Button partnerBtn = (Button) findViewById(R.id.connectToPartner) ; 	
		EditText textBox  = (EditText) findViewById(R.id.partnerId) ;	
		Button cntBtn = (Button) findViewById(R.id.connect) ; 	
		Button DiscBtn = (Button) findViewById(R.id.disconnect) ; 
		
				
		textView.setText("****");		 
		partnerBtn.setEnabled(false);
		textBox.setEnabled(false); 		
		DiscBtn.setEnabled(false);
		cntBtn.setEnabled(true);
		
	}
	
	
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			return rootView;
		}
	}
	
	@Override
	public void processFinish(String output) {
		
		try {
			manageReceivedMsg(output) ;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		

		
	}

}
